<template>
  <div class="search-box">
    <div>
      <a-space>
        <a-input-group>
          <a-input-search
            search-button
            :style="{ width: 'auto' }"
            placeholder="请输入入库单编号"
            v-model="currSelectSearch"
            @search="search"
          />
        </a-input-group>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export :rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.code"
        :title="item.name"
        :data-index="item.code"
        :width="150"
        align="center"
      >
        <template v-if="item.code === 'applyDetail'" #cell="{ record }">
          <a-typography-text
            class="Detail-item"
            type="primary"
            @click="See(record.product)"
          >
            查看
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'applyCause'" #cell="{ record }">
          <a-typography-text
            class="Detail-item"
            type="primary"
            @click="view(record.cause)"
          >
            查看
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'applyTime'" #cell="{ record }">
          {{ dayjs(record.applyTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else-if="item.code === 'createdAt'" #cell="{ record }">
          {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
        </template>

        <template
          v-else-if="item.code === 'inspectionStaffName'"
          #cell="{ record }"
        >
          {{ record.inspectionStaffName || '--' }}
        </template>

        <template
          v-else-if="item.code === 'warehouseStaffName'"
          #cell="{ record }"
        >
          {{ record.warehouseStaffName || '--' }}
        </template>

        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <div
            class="status"
            :style="{
              color: Status.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': Status.filter((ele) => ele.id === record.state)[0]
                  ?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ Status.filter((ele) => ele.id === record.state)[0]?.value }}
          </div>
        </template>
      </a-table-column>
      <a-table-column :width="100" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <a-tooltip content="入库详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDelivery(record.id)"
            />
          </a-tooltip>
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="待确认入库列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
  <ConfirmReceipt
    v-if="ReceiptId"
    v-model:visible="modelVisible"
    :receiptId="ReceiptId"
  />
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref,
    computed,
    onMounted,
    defineAsyncComponent,
  } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    GetWarehouseEntryAll,
    GetHeaderAll,
    putHeader,
    delWarehouseEntry,
    putWarehouseEntryState,
    getStorageAll,
  } from '@/api/inventory-management/warehousing-management/receiving-management/index';

  let ConfirmReceipt = defineAsyncComponent(
    () => import('./confirm-receipt/index.vue')
  );

  const router = useRouter();
  const title: string = '采购入库';
  const breadCrumb: string[] = ['库存管理', '入库管理', '采购入库'];
  const modelVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const modelCauseVisible = ref(false);
  const userState = ref();
  const beginTime = ref();
  const endTime = ref();
  const ownList = ref();
  const ReceiptId = ref();
  const saveUserId = ref<any>(
    JSON.parse(sessionStorage.getItem('loginInfo') as any)
  );

  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });

  // <a-typography-text v-if="record.state === 1" style="color: #999999">
  //           待入库
  //         </a-typography-text>
  //         <a-typography-text v-else type="success"> 已入库 </a-typography-text>

  const Status = [
    { id: 1, value: '待入库', backgroundColor: '#cccccc' },
    { id: 2, value: '已入库', backgroundColor: '#009933' },
    { id: 3, value: '已入库', backgroundColor: '#009933' },
    { id: 4, value: '已入库', backgroundColor: '#009933' },
  ];

  const getData = async (page: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (userState.value) msg.state = userState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (beginTime.value) msg.beginTime = beginTime.value;
      if (endTime.value) msg.endTime = endTime.value;

      let res = await getStorageAll({
        ...page,
        ...msg,
        entryType: 1,
      });

      if (res.content === null || res.content === undefined) {
        res.content = [];
      }

      res.content.map((item: any) => {
        item.show = false;
        return item;
      });

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const columns = [
    {
      code: 'number',
      isDefault: 1,
      name: '采购入库单号',
    },
    {
      code: 'entryWarehouseNumber',
      isDefault: 1,
      name: '关联收货单号',
    },
    {
      code: 'supplierName',
      isDefault: 1,
      name: '供应商名称',
    },
    {
      code: 'purchaseStaffName',
      isDefault: 1,
      name: '采购员',
    },
    {
      code: 'location',
      isDefault: 1,
      name: '暂存区域',
    },
    {
      code: 'entryStaffName',
      isDefault: 1,
      name: '收货人',
    },
    {
      code: 'inspectionStaffName',
      isDefault: 1,
      name: '质检员',
    },
    {
      code: 'okState',
      isDefault: 1,
      name: '入库状态',
    },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const headerSettingData = async () => {
    try {
      const res = await GetHeaderAll({
        userId: saveUserId.value.id,
        listType: 3,
      });
      headerSetting.list = res.extends ? res.extends : columns;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    userState.value = undefined;
    priorityData.value = undefined;
    beginTime.value = undefined;
    endTime.value = undefined;
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const onChange = (value: any) => {
    if (value !== undefined) {
      beginTime.value = value[0];
      endTime.value = value[1];
      tableRef.value.refreshPaging();
      tableRef.value.loadData();
    } else {
      tableRef.value.refreshPaging();
      tableRef.value.loadData();
    }
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        userId: 317,
        listType: 3,
        extend: JSON.stringify(val),
      };
      await putHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const SeeCauseDate = ref();
  const view = (content: string) => {
    SeeCauseDate.value = content;
    modelCauseVisible.value = true;
  };

  const searchState = (key: number) => {
    if (key === 1) {
      let into = JSON.parse(sessionStorage.getItem('loginInfo') as any);
      ownList.value = into.id;
      tableRef.value.loadData();
    } else {
      ownList.value = null;
      tableRef.value.loadData();
    }
  };

  const addBuyApply = () => {
    router.push({
      name: 'PurchaseReceiptAdd',
    });
  };

  const goDetails = (id?: number) => {
    router.push({
      name: 'ReceivingDetails',
      query: { id },
    });
  };

  const edit = (id: number) => {
    router.push({
      name: 'editApplyPurchase',
      query: { id },
    });
  };

  const goDelivery = async (id: number) => {
    modelVisible.value = true;
    ReceiptId.value = id;
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const SeeDate = ref();

  const See = (item: any) => {
    modelVisible.value = true;
    SeeDate.value = item;
  };

  const search = () => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const del = async (id: number) => {
    await delWarehouseEntry({ id });
    tableRef.value.loadData();
  };

  // 监听键盘回车，按了回车也会查询
  const keyDown = (e: any) => {
    if (e.keyCode === 13) {
      search();
    }
  };

  onMounted(() => {
    // 监听键盘事件
    window.addEventListener('keydown', keyDown);
  });
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }

  // :deep(.arco-space-item) {
  //   margin-top: 10px;
  // }
  .Detail-item {
    cursor: pointer;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
